/**
 * @ClassName Code03_InsertionSort
 * @Description: TODO
 * @Author: JCC
 * @CreateTime: 2023/11/3 20:54
 */

import java.util.Arrays;

/**
 * 插入排序
 */
public class Code03_InsertSort {

    // 正序排序
    // 思想：遇到前面比他大的就交换
    public static void InsertSort(int[] arr) {
        if (arr == null || arr.length < 2) {
            return;
        }
        for (int i = 1; i < arr.length; i++) {
            for (int j = i - 1; j >= 0 && arr[j] > arr[j + 1]; j--) {
                swap(arr, j, j + 1);
            }
        }
    }

    /**
     * 交换次数少一点
     *
     * @param arr
     */
    // 思想：给要插入的牌做好标记（缓存一下），遇到前面比他大的就后移，直到不比他大的位置，将缓存的牌插入
    public static void InsertSortOptimize(int[] arr) {
        if (arr == null || arr.length < 2) {
            return;
        }
        for (int i = 1; i < arr.length; i++) {
            int key = arr[i];
            int j = i - 1;
            for (; j >= 0 && arr[j] > key; j--) {
                arr[j + 1] = arr[j];
            }
            arr[j + 1] = key;
        }
    }

    public static void swap(int[] arr, int i, int j) {
        arr[i] = arr[i] ^ arr[j];
        arr[j] = arr[i] ^ arr[j];
        arr[i] = arr[i] ^ arr[j];
    }

    public static int[] generateRandomArray(int maxSize, int maxValue) {
        int[] array = new int[(int) (Math.random() * (maxSize + 1))];
        for (int i = 0; i < array.length; i++) {
            array[i] = (int) ((Math.random() * (maxValue + 1)) - (int) (Math.random() * maxValue));
        }
        return array;
    }

    public static boolean isEqual(int[] arr1, int[] arr2) {
        if (arr1 == null && arr2 == null) {
            return true;
        }
        if (arr1 == null ^ arr2 == null || arr1.length != arr2.length) {
            return false;
        }
        for (int i = 0; i < arr1.length; i++) {
            if (arr1[i] != arr2[i]) {
                return false;
            }
        }
        return true;
    }

    public static void test() {
        int testTimes = (int) (Math.random() * 9001 + 1000);
        int maxSize = 10;
        int maxValue = 100;
        System.out.println("测试开始");
        for (int i = 0; i < testTimes; i++) {
            int[] arr1 = generateRandomArray(maxSize,maxValue);
            int[] arr2 = Arrays.copyOf(arr1,arr1.length);
            InsertSortOptimize(arr1);
            Arrays.sort(arr2);
            if (!isEqual(arr1,arr2)) {
                System.out.println("结果出错");
                System.out.println(Arrays.toString(arr1));
                System.out.println(Arrays.toString(arr2));
                break;
            }
        }
        System.out.println("测试结束");
    }

    public static void main(String[] args) {
        test();
    }
}
